package JUC;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 豆包LU
 * @date 2023/5/10 22:48
 */
public class ThreadLocalLeakDemo {

    private static ThreadLocal<byte[]> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                byte[] data = new byte[1024 * 1024]; // 创建一个1MB大小的数组
                threadLocal.set(data); // 将数组设置到ThreadLocal中
                processData(); // 处理数据
                // 不主动清理ThreadLocal中的数据
            });
        }

        executorService.shutdown();
    }

    private static void processData() {
        try {
            byte[] data = threadLocal.get(); // 从ThreadLocal中获取数据
            System.out.println("Thread: " + Thread.currentThread().getId() + " Data: " + data);
        }finally {
            threadLocal.remove();
        }
    }
}
